// Copyright (C) ZHENG Zhong <heavyzheng nospam-at gmail D0T com>
// http://www.zhengzhong.net/
//
// $Id: evaluate_xpath.hpp 318 2009-03-02 14:03:21Z heavyzheng $
//

#ifndef ZZHENG_EXAMPLE_EVALUATE_XPATH_HPP_20080811__
#define ZZHENG_EXAMPLE_EVALUATE_XPATH_HPP_20080811__

#include <zzheng/xml/dom.hpp>

#include <cassert>
#include <exception>
#include <string>
#include <iostream>

namespace zzheng {
namespace example {

    inline
    int evaluate_xpath(const char* xml_str) {
        try {
            // Parse the XML string into a document.
            xml::dom::parser parser;
            std::auto_ptr<xml::dom::document> doc(parser.parse_string(xml_str));
            assert(doc.get() != 0);

            // TODO:
            xml::dom::xpath xpath;
            xpath.add_namespace("http://en.wikipedia.org/", "wikipedia");

            std::string expr_1 = "/*/*";
            std::cout << "Evaluating: " << expr_1 << std::endl;
            xml::dom::xpath_result result_1 = xpath.evaluate(expr_1, *doc);
            if (result_1.type() == xml::dom::xpath_node_set) {
                std::cout << "result (node_set) is: " << std::endl;
                xml::dom::node_set& nodes = result_1.as_node_set();
                for (xml::dom::node_set::iterator i = nodes.begin(); i != nodes.end(); ++i) {
                    std::cout << "    " << i->name() << std::endl;
                }
                
            } else {
                std::cout << "error: result is not a node set." << std::endl;
            }

            std::string expr_2 = "./*";
            std::cout << "Evaluating: " << expr_2 << std::endl;
            xml::dom::xpath_result result_2 = xpath.evaluate(expr_2, *(doc->root()));
            if (result_2.type() == xml::dom::xpath_node_set) {
                std::cout << "result (node_set) is: " << std::endl;
                xml::dom::node_set& nodes = result_2.as_node_set();
                for (xml::dom::node_set::iterator i = nodes.begin(); i != nodes.end(); ++i) {
                    std::cout << "    " << i->name() << std::endl;
                }
            } else {
                std::cout << "error: result is not a node set." << std::endl;
            }
            
            return 0;

        } catch (const xml::dom::dom_error& ex) {
            std::cerr << "Error (dom_error): " << ex.what() << std::endl;
            return 1;
        } catch (const std::exception& ex) {
            std::cerr << "Error (std::exception): " << ex.what() << std::endl;
            return 1;
        } catch (...) {
            std::cerr << "Error (unknown exception)" << std::endl;
            return 1;
        }
    }

} // namespace zzheng::example
} // namespace zzheng


#endif // ZZHENG_EXAMPLE_EVALUATE_XPATH_HPP_20080811__



